<template>
  <!-- 查询条件 -->
  <div class="search-container">
    <el-card class="search-card">
      <div class="search-header">
        <h3>地陪搜索</h3>
        <p>查找您需要的地陪信息</p>
      </div>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input v-model="searchObj.username" placeholder="用户名" clearable>
            <template #prefix>
              <i class="el-icon-user"></i>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchObj.gender" placeholder="性别" clearable style="width: 100%;">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchObj.position" placeholder="位置" clearable>
            <template #prefix>
              <i class="el-icon-location"></i>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <div class="search-actions">
            <el-button type="primary" @click="handleSearch" round>
              <i class="el-icon-search"></i> 查询
            </el-button>
            <el-button @click="handleReset" round>
              <i class="el-icon-refresh"></i> 重置
            </el-button>
            <el-button type="success" @click="handleAdd" round>
              <i class="el-icon-plus"></i> 添加地陪
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>

  <!-- 数据表格 -->
  <el-card class="table-card">
    <template #header>
      <div class="table-header">
        <h3>地陪列表</h3>
        <p>共 {{ tableData.totalCount || 0 }} 条记录</p>
      </div>
    </template>

    <el-table :data="tableData.data" style="width: 100%" border>
      <el-table-column label="用户名" width="120">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>用户名: {{ scope.row.username }}</div>
            </template>
            <template #reference>
              <el-tag type="primary">{{ scope.row.username }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="100">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>性别: {{ scope.row.gender === 0 ? '女' : '男'}}</div>
            </template>
            <template #reference>
              <el-tag :type="scope.row.gender === 0 ? 'danger' : 'primary'">
                {{ scope.row.gender === 0 ? '女' : '男' }}
              </el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="130">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>手机号: {{ scope.row.phone }}</div>
            </template>
            <template #reference>
              <el-tag type="info">{{ scope.row.phone }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="180">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>邮箱: {{ scope.row.email }}</div>
            </template>
            <template #reference>
              <el-tag type="success">{{ scope.row.email }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="位置" width="100">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>位置: {{ scope.row.position }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.position }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="照片" width="100">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>照片: {{ scope.row.image}}</div>
              <el-image
                  :src="getOssImageUrl(scope.row.image)"
                  style="width: 100px; height: 100px"
                  fit="cover"
                  :preview-src-list="[getOssImageUrl(scope.row.image)]"
                  :initial-index="0"
              />
            </template>
            <template #reference>
              <el-image
                  :src="getOssImageUrl(scope.row.image)"
                  style="width: 40px; height: 40px"
                  fit="cover"
                  lazy
                  hide-on-click-modal
                  class="guide-avatar"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="90">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>年龄: {{ scope.row.age }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.age }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="身高" width="90">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>身高: {{ scope.row.height }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.height}}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="体重" width="90">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>体重: {{ scope.row.weight }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.weight }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="100">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>价格: {{ scope.row.price }}</div>
            </template>
            <template #reference>
              <el-tag type="warning">{{ scope.row.price }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="评分" width="180">
        <template #default="scope">
          <div v-if="scope.row.rate !== undefined">
            <el-rate
                v-model="scope.row.rate"
                disabled
                show-score
                score-template="{value}分"
                :max="5"
            />
          </div>
          <div v-else>
            <el-skeleton :rows="1" animated v-if="scope.row.loadingRate" />
            <span v-else>暂无评分</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" round>
            <i class="el-icon-edit"></i> 修改
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              round
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="searchObj.currentPage"
          v-model:page-size="searchObj.pageSize"
          :page-sizes="[5,10, 20, 30, 50]"
          :total="tableData.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
      />
    </div>
  </el-card>

  <!-- 添加对话框 -->
  <el-dialog v-model="addDialogVisible" title="添加地陪信息" width="500px" class="custom-dialog">
    <el-form :model="newGuideData" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="newGuideData.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="newGuideData.gender" placeholder="请选择性别">
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="newGuideData.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="newGuideData.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="位置">
        <el-input v-model="newGuideData.position" placeholder="请输入位置"></el-input>
      </el-form-item>
      <el-form-item label="照片">
        <el-input v-model="newGuideData.image" readonly placeholder="请上传照片">
          <template #append>
            <el-button @click="handleImageUpload('add')">
              <el-icon><Upload /></el-icon> 上传
            </el-button>
          </template>
        </el-input>
        <div v-if="newGuideData.image" class="image-preview">
          <el-image
              :src="getOssImageUrl(newGuideData.image)"
              style="width: 100px; height: 100px"
              fit="cover"
              :preview-src-list="[getOssImageUrl(newGuideData.image)]">
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model.number="newGuideData.age" placeholder="请输入年龄"></el-input>
      </el-form-item>
      <el-form-item label="身高">
        <el-input-number
            v-model="newGuideData.height"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入身高">
          <template #append>cm</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="体重">
        <el-input-number
            v-model="newGuideData.weight"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入体重">
          <template #append>kg</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model.number="newGuideData.price" placeholder="请输入价格"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false" round>取消</el-button>
        <el-button type="primary" @click="saveAdd" round>保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑对话框 -->
  <el-dialog v-model="editDialogVisible" title="编辑导游信息" width="500px" class="custom-dialog">
    <el-form :model="currentEditData" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="currentEditData.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="currentEditData.gender" placeholder="请选择性别">
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="currentEditData.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="currentEditData.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="位置">
        <el-input v-model="currentEditData.position" placeholder="请输入位置"></el-input>
      </el-form-item>
      <el-form-item label="照片">
        <el-input v-model="currentEditData.image" readonly placeholder="请上传照片">
          <template #append>
            <el-button @click="handleImageUpload('edit')">
              <el-icon><Upload /></el-icon> 上传
            </el-button>
          </template>
        </el-input>
        <div v-if="currentEditData.image" class="image-preview">
          <el-image
              :src="getOssImageUrl(currentEditData.image)"
              style="width: 100px; height: 100px"
              fit="cover"
              :preview-src-list="[getOssImageUrl(currentEditData.image)]">
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model.number="currentEditData.age" placeholder="请输入年龄"></el-input>
      </el-form-item>
      <el-form-item label="身高">
        <el-input-number
            v-model="currentEditData.height"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入身高">
          <template #append>cm</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="体重">
        <el-input-number
            v-model="currentEditData.weight"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入体重">
          <template #append>kg</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model.number="currentEditData.price" placeholder="请输入价格"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false" round>取消</el-button>
        <el-button type="primary" @click="saveEdit" round>保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上传对话框 -->
  <el-dialog v-model="uploadDialogVisible" title="上传图片" width="500px" class="custom-dialog">
    <div class="upload-container">
      <input
          type="file"
          accept="image/*"
          @change="handleFileChange"
          ref="fileInput"
          style="display: none"
      >
      <el-button
          @click="$refs.fileInput.click()"
          type="primary"
          :loading="uploadLoading"
          round
          size="large">
        <el-icon><Upload /></el-icon>
        {{ uploadLoading ? '上传中...' : '选择图片文件' }}
      </el-button>
      <p class="upload-tip">
        支持 JPG/PNG 格式，建议尺寸 300x300
      </p>
    </div>
  </el-dialog>
</template>

<script setup>
import uploadApi from '../../api/upload_api.js'
import {ref, onMounted} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import {Picture, Upload} from '@element-plus/icons-vue'
import m_guide_api from "../../api/manager/m_guide_api.js";
import mRateApi from '@/api/manager/m_rate_api.js'

//处理OSS图片URL
const getOssImageUrl = (imageUrl) => {
  // 如果没有图片URL，返回默认图片
  if (!imageUrl || imageUrl.trim() === '') {
    return 'https://via.placeholder.com/40x40?text=No+Image';
  }
  // 如果已经是完整URL，直接返回
  if (imageUrl.startsWith('http')) {
    return imageUrl;
  }
  // 如果是相对路径，构建完整URL
  const bucketName = 'java-dz';
  const endpoint = 'oss-cn-beijing.aliyuncs.com';
  return `https://${bucketName}.${endpoint}/${imageUrl}`;
}

//定义绑定的数据
//表格中的数据
const tableData = ref({})
//查询数据
const searchObj = ref({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0,
  username: '',
  gender: '',
  phone: '',
  email: '',
  position: '',
  image: '',
  age: '',
  height: '',
  weight: '',
  price: ''
})

//添加对话框相关数据
const addDialogVisible = ref(false)
const newGuideData = ref({
  username: '',
  gender: 1,
  phone: '',
  email: '',
  position: '',
  image: '',
  age: '',
  height: '',
  weight: '',
  price: ''
})

//编辑对话框相关数据
const editDialogVisible = ref(false)
const currentEditData = ref({})

//上传相关数据
const uploadDialogVisible = ref(false)
const currentUploadType = ref('') // 'add' 或 'edit'
const uploadLoading = ref(false)

//页面加载后要挂载的数据
onMounted(async () => {
  await loadData();
})

//加载数据方法
const loadData = async () => {
  tableData.value = await m_guide_api.page(searchObj.value);
  // 加载每个地陪的评分
  await loadRatesForGuides();
}

// 为所有地陪加载评分
const loadRatesForGuides = async () => {
  if (!tableData.value.data || tableData.value.data.length === 0) return;

  try {
    // 创建一个数组，用于保存每个地陪的评分
    const promises = tableData.value.data.map(async (guide) => {
      try {
        // 为每个地陪添加loading状态
        guide.loadingRate = true;
        // 调用接口获取该地陪的评分
        const res = await mRateApi.getRate({ guideId: guide.id });
        // 将评分保存到guide对象中
        guide.rate = res ? parseFloat(res.toFixed(1)) : 0;
      } catch (error) {
        console.error(`加载地陪${guide.id}评分失败:`, error);
        guide.rate = 0;
      } finally {
        guide.loadingRate = false;
      }
    });

    await Promise.all(promises);
  } catch (error) {
    console.error('批量加载评分失败:', error);
  }
}

//查询功能
const handleSearch = async () => {
  searchObj.value.currentPage = 1;
  await loadData();
}

//重置查询条件
const handleReset = async () => {
  searchObj.value = {
    currentPage: 1,
    pageSize: 10,
    totalCount: 0,
    username: '',
    gender: '',
    phone: '',
    email: '',
    position: '',
    image: '',
    age: '',
    height: '',
    weight: '',
    price: ''
  }
  await loadData();
}

//添加功能
const handleAdd = () => {
  //重置表单数据
  newGuideData.value = {
    username: '',
    gender: 1,
    phone: '',
    email: '',
    position: '',
    image: '',
    age: '',
    height: '',
    weight: '',
    price: ''
  }
  //显示添加对话框
  addDialogVisible.value = true
}

const saveAdd = async () => {
  console.log("准备提交的数据:", newGuideData.value);
  try {
    //调用API添加数据
    await m_guide_api.add(newGuideData.value)
    //重新加载数据
    await loadData()
    //关闭对话框
    addDialogVisible.value = false
    //显示成功消息
    ElMessage.success('添加成功')
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message)
  }
}

//编辑功能
const handleEdit = (index, row) => {
  //将当前行数据复制到编辑对象中
  currentEditData.value = {...row}
  //显示编辑对话框
  editDialogVisible.value = true
}

const saveEdit = async () => {
  console.log("准备提交的数据:", currentEditData.value);
  try {
    //调用API更新数据
    await m_guide_api.edit(currentEditData.value)
    //重新加载数据
    await loadData()
    //关闭对话框
    editDialogVisible.value = false
    //显示成功消息
    ElMessage.success('修改成功')
  } catch (error) {
    ElMessage.error('修改失败: ' + error.message)
  }
}

//删除功能
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      `确定要删除导游 "${row.username}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      //调用API删除数据
      await m_guide_api.del(row.id)
      //重新加载数据
      await loadData()
      //显示删除成功消息
      ElMessage.success('删除成功')
    } catch (error) {
      //处理删除失败的情况
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    //用户取消删除
    ElMessage.info('已取消删除')
  })
}

//分页功能
const handleSizeChange = async (val) => {
  searchObj.value.pageSize = val;
  searchObj.value.currentPage = 1;// 页大小改变时重置到第一页
  await loadData();
}

const handleCurrentChange = async (val) => {
  searchObj.value.currentPage = val;
  await loadData();
}

//图片上传功能
const handleImageUpload = (type) => {
  currentUploadType.value = type
  uploadDialogVisible.value = true
}

const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }

  uploadLoading.value = true
  try {
    const result = await uploadApi.upload(file)
    console.log('上传结果:', result)

    if (!result || typeof result !== 'string') {
      throw new Error('上传失败：服务器未返回有效数据')
    }

    // 使用 result.data（这是图片URL）
    if (currentUploadType.value === 'add') {
      newGuideData.value.image = result
    } else {
      currentEditData.value.image = result
    }

    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error('上传失败: ' + error.message)
  } finally {
    uploadLoading.value = false
    event.target.value = ''
  }
}

</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(168, 192, 235, 0.2);
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #333;
  border: none;
}

:deep(.search-card .el-card__body) {
  padding: 25px;
}

.search-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.search-header p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.search-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
}

.table-card {
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(168, 192, 235, 0.2);
  border: none;
}

:deep(.table-card .el-card__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  border-radius: 15px 15px 0 0 !important;
  padding: 20px;
  border: none;
}

.table-header h3 {
  margin: 0 0 5px 0;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.table-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.custom-dialog {
  border-radius: 15px;
  overflow: hidden;
}

:deep(.custom-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  padding: 20px;
  border-radius: 15px 15px 0 0 !important;
}

:deep(.custom-dialog .el-dialog__title) {
  color: #409eff;
  font-weight: 600;
}

:deep(.el-table) {
  border-radius: 10px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
}

.guide-avatar {
  border-radius: 50%;
  border: 2px solid #409eff;
  transition: all 0.3s ease;
}

.guide-avatar:hover {
  transform: scale(1.1);
  border-color: #67c23a;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f0f9ff;
  color: #909399;
  border-radius: 50%;
}

.image-preview {
  margin-top: 15px;
  text-align: center;
}

.upload-container {
  text-align: center;
  padding: 30px 20px;
}

.upload-tip {
  margin-top: 15px;
  color: #909399;
  font-size: 14px;
}

@media (max-width: 768px) {
  .search-actions {
    flex-wrap: wrap;
    gap: 8px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table th) {
    font-size: 12px;
    padding: 8px 0;
  }
}
</style>
